package com.nbsaas.boot.lock.impl;

import com.nbsaas.boot.lock.api.LockService;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class MemoryLockService implements LockService {

    private final ConcurrentMap<String, Lock> lockMap = new ConcurrentHashMap<>();

    @Override
    public boolean lock(String key) {
        Lock lock = lockMap.get(key);
        if (lock != null) {
            // 如果锁已经存在，则直接尝试获取锁，避免阻塞
            return lock.tryLock();
        }
        // 锁不存在时创建新的锁并尝试获取
        lock = new ReentrantLock();
        Lock existingLock = lockMap.putIfAbsent(key, lock);
        if (existingLock != null) {
            // 如果在插入时，锁已被其他线程创建，直接尝试获取锁
            return existingLock.tryLock();
        }
        // 如果成功插入新锁，尝试获取锁
        return lock.tryLock();
    }

    @Override
    public boolean lock(String key, long timeout, TimeUnit unit) {
        Lock lock = lockMap.get(key);
        if (lock != null) {
            // 如果锁已经存在，直接尝试获取锁
            try {
                return lock.tryLock(timeout, unit);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                return false;
            }
        }
        // 锁不存在时创建新的锁并尝试获取
        lock = new ReentrantLock();
        Lock existingLock = lockMap.putIfAbsent(key, lock);
        if (existingLock != null) {
            // 如果插入时，锁已存在，直接尝试获取锁
            try {
                return existingLock.tryLock(timeout, unit);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                return false;
            }
        }
        // 如果成功插入新锁，尝试获取锁
        try {
            return lock.tryLock(timeout, unit);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return false;
        }
    }

    @Override
    public boolean unlock(String key) {
        Lock lock = lockMap.get(key);
        if (lock != null) {
            lock.unlock();  // 释放锁
            lockMap.remove(key);  // 解锁后移除锁
            return true;
        }
        return false;
    }

    @Override
    public boolean isLocked(String key) {
        Lock lock = lockMap.get(key);
        return lock != null && ((ReentrantLock) lock).isLocked();
    }
}
